package com.gz.mylife.app.keys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.gz.mylife.R;
import com.gz.mylife.http.AsyncHttpClient;
import com.gz.mylife.http.AsyncHttpResponseHandler;
import com.gz.mylife.http.RequestParams;
import com.gz.mylife.util.PrefUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tencent.utils.Util.Statistic;
import com.zl.smartmall.library.po.KeysData;
import com.zl.smartmall.library.po.KeysData.Ref;
import com.zl.smartmall.library.util.Constants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class KeysFragment extends Fragment{
	private View mConvertView;
	private PullToRefreshListView lvkeys;
	private  List<Ref> mKeys = new ArrayList<KeysData.Ref>();
	private Context mContext;
	private Map<Integer, Boolean> isChecked;
	private  KeysAdapter keysAdapter;
	private Button transfer;
	int i = 0;
	private RelativeLayout logo_info;
	private ProgressBar pb_progress;
	private TextView tv_hint;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mConvertView == null) {
			mConvertView = inflater.inflate(R.layout.activity_doorlist,
					container, false);
		}
		mContext = getActivity().getApplicationContext();
		logo_info = (RelativeLayout) mConvertView.findViewById(R.id.logo_info);
		pb_progress = (ProgressBar) mConvertView.findViewById(R.id.pb_progress);
		tv_hint = (TextView) mConvertView.findViewById(R.id.tv_hint);
		transfer = (Button) mConvertView.findViewById(R.id.transfer);
		transfer.setVisibility(View.GONE);
		lvkeys = (PullToRefreshListView) mConvertView.findViewById(R.id.listchance);
		lvkeys.setMode(Mode.DISABLED);
		keysAdapter = new KeysAdapter();
		lvkeys.setAdapter(keysAdapter);
		initData();
		logo_info.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pb_progress.setVisibility(View.VISIBLE);
				tv_hint.setVisibility(View.VISIBLE);
				tv_hint.setText("卖命加载中...");
				getDataFromServer(Constants.KEYS_URL);
			}
		});
		return mConvertView;
	}
	// 解析Json 数据
	private void parseData(String content) {
		Gson gson = new Gson();
		KeysData mkeysData = gson.fromJson(content, KeysData.class);
		mkeysData.ref.addAll(mkeysData.msg);
		mKeys = mkeysData.ref;
		if (mKeys.size()>0) {
			logo_info.setVisibility(View.GONE);
			keysAdapter.notifyDataSetChanged();
			initCheckedState();
		}else{
			logo_info.setVisibility(View.VISIBLE);
			pb_progress.setVisibility(View.GONE);
			tv_hint.setText("暂无钥匙");
		}

		// 转授权 事件监听 (跳页面)
		/*transfer.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) { 

				ArrayList<String> divList = new ArrayList<String>();// 初始化一个集合 用来存放转授权选中的钥匙
				if (isChecked!=null) {

					for (int j = 0; j < isChecked.size(); j++) {
						Boolean result = isChecked.get(j);

						if (result) {
							String div_sn = mKeys.get(j).getController_sn();
							divList.add(div_sn);
						}
					}
					if (divList.size()>0) {// 跳页面之前，判断有没有选择钥匙
						Intent i = new Intent(getActivity(),TransferActivity.class);
						i.putStringArrayListExtra("divList", divList);
						startActivity(i);
					}else{

						Toast.makeText(getActivity(), "未选择钥匙", 0).show();
					}

				}else{
				}

			}

		});*/
	}
	// 初始化数据
	protected void initData() {
         
		String url = Constants.KEYS_URL;
		String strPrefData = PrefUtils.getStrPrefData(mContext, url, "-1");// 读缓存
		
		mKeys.clear();
		if (strPrefData.equals("-1")) {// 没有缓存时，从网络获取
			getDataFromServer(url);
		}else{// 有缓存解析数据
			parseData(strPrefData);
		}

	}
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		getDataFromServer(Constants.KEYS_URL);
	}
	private void getDataFromServer(String url) {

		AsyncHttpClient httpClient=new AsyncHttpClient();
		RequestParams params=new RequestParams();
		params.put("phone_num", PrefUtils.getStrPrefData(mContext, "phone_num", null));

		httpClient.get(url ,params,new AsyncHttpResponseHandler(){

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				parseData(content);
				PrefUtils.setStrPrefData(mContext, Constants.KEYS_URL, content);// 写入缓存
			}
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
			}
		});
	}
	// 钥匙列表的适配器
	public class KeysAdapter extends BaseAdapter{
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mKeys.size();
		}
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mKeys.get(position);
		}
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View itemView = View.inflate(mContext, R.layout.item_keys, null);
			TextView tvAddress = (TextView) itemView.findViewById(R.id.tv_address);
			TextView tvTime = (TextView) itemView.findViewById(R.id.tv_time);
			Ref ref = mKeys.get(position);
			tvAddress.setText(ref.getName()+"("+ref.getController_name()+"-"+ref.getDirection()+")");
			tvTime.setText("有效期："+ref.getEnd_date());
			return itemView;
		}

	}
	//初始化radioButton的状态
	private void initCheckedState() {

		isChecked = new HashMap<Integer, Boolean>();
		for (int i = 0; i < mKeys.size(); i++) {
			isChecked.put(i, false);
		}

		// ListView 条目监听(钥匙选中)
		/*lvkeys.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				RadioButton rbCheck = (RadioButton) view.findViewById(R.id.rb_check);
				boolean checked = rbCheck.isChecked();
				if (checked) {
					rbCheck.setChecked(false);
					isChecked.remove(position-1);
					isChecked.put(position-1, false);
				}else{
					rbCheck.setChecked(true);
					isChecked.remove(position-1);
					isChecked.put(position-1, true);
				}

			}});*/
	}
}
